package com.usian.reggie.controller;

import com.usian.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file){
        String newFileName="";
        try {
            String filename = file.getOriginalFilename(); //d:/abc/name.jpg
            String s = filename.substring(filename.lastIndexOf(".")); //name

            //重新生成文件名字
            newFileName = UUID.randomUUID().toString().concat(s);

            //上传文件
            //2. 构建文件存储的目录
            File dir = new File(path);
            if(!dir.exists()){
                dir.mkdirs();
            }
            File targerFile =new File(dir,newFileName);
            file.transferTo(targerFile);


        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newFileName);
    }

    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            File targerFile= new File(path,name);
            FileInputStream inputStream =new FileInputStream(targerFile);

            //得到响应的输出流
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] buf = new byte[1024];
            int length =0;
            //边读边写

            while((length=inputStream.read(buf))!=-1){
                outputStream.write(buf,0,length);
            }
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
